import React, { useState, useEffect } from "react";
import { OperationalUnit } from "@/api/entities";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { 
  Plus, 
  Search, 
  Settings,
  Users,
  Building,
  Hammer,
  Eye,
  Edit,
  Trash2
} from "lucide-react";

import OperationalUnitCard from "../components/operational-units/OperationalUnitCard";
import OperationalUnitForm from "../components/operational-units/OperationalUnitForm";

export default function OperationalUnits() {
  const [units, setUnits] = useState([]);
  const [filteredUnits, setFilteredUnits] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingUnit, setEditingUnit] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedType, setSelectedType] = useState("all");
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    filterUnits();
  }, [units, searchTerm, selectedType]);

  const loadData = async () => {
    setIsLoading(true);
    try {
      const unitsData = await OperationalUnit.list("-created_date");
      setUnits(Array.isArray(unitsData) ? unitsData : []);
    } catch (error) {
      console.error("加载作业单位数据失败:", error);
      setUnits([]);
    }
    setIsLoading(false);
  };

  const filterUnits = () => {
    let filtered = units;

    if (searchTerm) {
      filtered = filtered.filter(unit =>
        unit.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        unit.contact_person?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (selectedType !== "all") {
      filtered = filtered.filter(unit => unit.type === selectedType);
    }

    setFilteredUnits(filtered);
  };

  const handleSubmit = async (unitData) => {
    try {
      if (editingUnit) {
        await OperationalUnit.update(editingUnit.id, unitData);
      } else {
        await OperationalUnit.create(unitData);
      }
      setShowForm(false);
      setEditingUnit(null);
      loadData();
    } catch (error) {
      console.error("保存作业单位失败:", error);
      alert("保存作业单位失败: " + (error.message || "未知错误"));
    }
  };

  const handleEdit = (unit) => {
    setEditingUnit(unit);
    setShowForm(true);
  };

  const handleDelete = async (unitId) => {
    if (window.confirm("确定要删除此作业单位吗？此操作可能影响现有的工作规划。")) {
      try {
        await OperationalUnit.delete(unitId);
        loadData();
      } catch (error) {
        console.error("删除作业单位失败:", error);
        alert("删除作业单位失败，请稍后重试。");
      }
    }
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingUnit(null);
  };

  const getStats = () => {
    return {
      total: units.length,
      constructionUnits: units.filter(u => u.type === 'constructionUnit').length,
      designUnits: units.filter(u => u.type === 'designUnit').length,
      supervisionUnits: units.filter(u => u.type === 'supervisionUnit').length
    };
  };

  const stats = getStats();

  return (
    <div className="p-6 space-y-6 bg-gray-50 min-h-screen">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-6 mb-8">
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">作业单位管理</h1>
            <p className="text-gray-600">管理施工单位、设计单位、监理单位的资源承载能力配置</p>
          </div>
          <Button 
            onClick={() => setShowForm(true)}
            className="bg-green-600 hover:bg-green-700 flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            新建作业单位
          </Button>
        </div>

        {/* Search and Filters */}
        <div className="flex flex-col lg:flex-row gap-4 mb-6">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <Input
              placeholder="搜索单位名称或联系人..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10"
            />
          </div>
          <select
            value={selectedType}
            onChange={(e) => setSelectedType(e.target.value)}
            className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 text-gray-700 bg-white"
          >
            <option value="all">所有类型</option>
            <option value="constructionUnit">施工单位</option>
            <option value="designUnit">设计单位</option>
            <option value="supervisionUnit">监理单位</option>
          </select>
        </div>

        {/* Statistics */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="bg-gradient-to-r from-green-50 to-green-100 border-green-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-green-600">总单位数</p>
                  <p className="text-2xl font-bold text-green-700">{stats.total}</p>
                </div>
                <Building className="w-8 h-8 text-green-500" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-r from-blue-50 to-blue-100 border-blue-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-blue-600">施工单位</p>
                  <p className="text-2xl font-bold text-blue-700">{stats.constructionUnits}</p>
                </div>
                <Hammer className="w-8 h-8 text-blue-500" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-r from-purple-50 to-purple-100 border-purple-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-purple-600">设计单位</p>
                  <p className="text-2xl font-bold text-purple-700">{stats.designUnits}</p>
                </div>
                <Eye className="w-8 h-8 text-purple-500" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-gradient-to-r from-orange-50 to-orange-100 border-orange-200">
            <CardContent className="p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm font-medium text-orange-600">监理单位</p>
                  <p className="text-2xl font-bold text-orange-700">{stats.supervisionUnits}</p>
                </div>
                <Settings className="w-8 h-8 text-orange-500" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Unit Form */}
        {showForm && (
          <OperationalUnitForm
            unit={editingUnit}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
          />
        )}

        {/* Units Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
          {isLoading ? (
            Array(6).fill(0).map((_, i) => (
              <Card key={i} className="animate-pulse">
                <CardHeader>
                  <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="h-3 bg-gray-200 rounded"></div>
                    <div className="h-3 bg-gray-200 rounded w-2/3"></div>
                  </div>
                </CardContent>
              </Card>
            ))
          ) : filteredUnits.length === 0 ? (
            <div className="col-span-full text-center py-12">
              <Users className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-gray-900 mb-2">暂无作业单位</h3>
              <p className="text-gray-500 mb-6">添加作业单位以管理资源承载能力</p>
              <Button 
                onClick={() => setShowForm(true)}
                className="bg-green-600 hover:bg-green-700"
              >
                <Plus className="w-4 h-4 mr-2" />
                新建作业单位
              </Button>
            </div>
          ) : (
            filteredUnits.map((unit) => (
              <OperationalUnitCard
                key={unit.id}
                unit={unit}
                onEdit={handleEdit}
                onDelete={handleDelete}
              />
            ))
          )}
        </div>
      </div>
    </div>
  );
}